﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "CmdFinishDrawCustomizedProfileColumn.h"

#include "IDocument.h"
#include "GmUiStructureCommandRegister.h"
#include "CmdStatusUtils.h"
#include "IUiDocument.h"
#include "IEditMode.h"
#include "IPlane.h"
#include "IModelView.h"
#include "IModelLine.h"
#include "StructureEditModeTypes.h"
#include "INewViewProfileEditModeBehavior.h"
#include "ProfileUsedModelLineUtils.h"
#include "UiCommonDialog.h"
#include "StructureEditProfileUtils.h"
#include "UserTransactionGroupUtils.h"
#include "IUserTransaction.h"
#include "IFamilyConfigElement.h"
#include "BuiltInStructureFamilies.h"
#include "FamilyLoadOptionsDefaultImpl.h"
#include "FamilyUtils.h"
#include "ICommandManager.h"
#include "CommandParameters.h"
#include "StructureCmdParamIds.h"
#include "IFamily.h"
#include "IFamilyType.h"
#include "AlgorithmCurveOperate.h"
#include "StructureCustomizedProfileInstanceUtils.h"
#include "UiDocumentViewUtils.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

REGISTER_GM_COMMAND(CmdFinishDrawCustomizedProfileColumn)

gcmp::CmdFinishDrawCustomizedProfileColumn::CmdFinishDrawCustomizedProfileColumn(const std::wstring& cmdId)
    : GbmpCommandBase(cmdId)
{
}

bool gcmp::CmdFinishDrawCustomizedProfileColumn::IsEnabled() const
{
    if (!CommandBase::IsEnabled())
    {
        return false;
    }

    CMD_ONLY_ENABLE_IN_PROJECT_ENVIRONMENT
}

bool gcmp::CmdFinishDrawCustomizedProfileColumn::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_PROJECT_ENVIRONMENT
}

gcmp::OwnerPtr<gcmp::IAction> gcmp::CmdFinishDrawCustomizedProfileColumn::ExecuteCommand(const CommandParameters& cmdParams)
{
    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    IUiDocument* pUIDoc = UiDocumentViewUtils::GetCurrentUiDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pUIDoc, L"pUIDoc为空",L"GDMPLab",L"2024-03-30");

    IModelView* pModelView = UiDocumentViewUtils::GetCurrentModelView();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pModelView, L"pModelView为空",L"GDMPLab",L"2024-03-30");

    const IEditMode* pProfileEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::NewViewCustomizedProfileModeType);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pProfileEditMode, L"pProfileEditMode为空",L"GDMPLab",L"2024-03-30");

    const INewViewProfileEditModeBehavior* pProfileEditModeBehavior = quick_cast<const INewViewProfileEditModeBehavior>(pProfileEditMode->GetEditModeBehavior());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pProfileEditModeBehavior, L"pProfileEditModeBehavior为空",L"GDMPLab",L"2024-03-30");
    
    // 获取当前文档里的轮廓线
    std::vector<IModelLine*> modelLines;
    ProfileUsedModelLineUtils::GetStructureProfileModelLinesInCurrDoc(pDoc, modelLines);

    if (modelLines.empty())
    {
        UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"轮廓为空，无法完成绘制轮廓！"), (int)UiCommonDialog::ButtonType::OK);
        return nullptr;
    }

    // 检查轮廓线是否合法
    OwnerPtr<IPlane> opWorkPlane = pModelView->GetWorkPlane();
    if (!StructureEditProfileUtils::CheckForValidLoops(modelLines, opWorkPlane->GetCoordinate(), false, true))
    {
        return nullptr;
    }

    // 得到封闭轮廓线
    OwnerPtr<IPolyCurve> opLoop;
    {
        std::vector<OwnerPtr<IPolygon>> opPolygonList;
        EnLoopsState loopsState = StructureCustomizedProfileInstanceUtils::GeneratePolygonFromModelLines(modelLines, pModelView, opPolygonList);
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(EnLoopsState::LOOPVALID == loopsState, L"轮廓无效",L"GDMPLab",L"2024-03-30");
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opPolygonList.size() == 1, L"封闭的轮廓只能有一个",L"GDMPLab",L"2024-03-30");

        IPolygon* pIPolygon = opPolygonList[0].get();
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pIPolygon, L"pIPolygon为空",L"GDMPLab",L"2024-03-30");
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pIPolygon->GetPolyCurveCount() == 1, L"封闭的轮廓只能有一个",L"GDMPLab",L"2024-03-30");

        opLoop = TransferOwnership(pIPolygon->GetPolyCurve(0));
    }
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opLoop, L"opLoop为空",L"GDMPLab",L"2024-03-30");

    // 生成族名
    std::wstring familyName = StructureCustomizedProfileInstanceUtils::GenerateUniqueFamilyName(pDoc, pProfileEditModeBehavior->GetEditingFamilyName());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(!familyName.empty(), L"familyName无效",L"GDMPLab",L"2024-03-30");

    const IFamilyConfigElement* pIFamilyConfigElement = IFamilyConfigElement::GetFamilyConfigElementByName(pDoc, familyName);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(!pIFamilyConfigElement, L"FamilyConfig已经创建",L"GDMPLab",L"2024-03-30");

    // 根据Loop生成族
    std::wstring familyPath = BuiltInStructureFamilies::CreateCustomizedProfileColumnFamilyDocument(familyName, opLoop.get());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(!familyPath.empty(), L"创建族文档失败",L"GDMPLab",L"2024-03-30");

    // 加载族文档
    std::wstring errorMsg;
    FamilyLoadOptionsDefaultImpl familyLoadOptionsImpl(gcmp::FamilyFoundStrategy::FF_Overwrite);

    OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"加载族文档"), true);

    IFamily* pIFamily = FamilyUtils::LoadFamily(pDoc, familyPath, errorMsg, &familyLoadOptionsImpl);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pIFamily, L"pIFamily为空",L"GDMPLab",L"2024-03-30");

    ut->Commit();

    const std::vector<const IFamilyType*> familyTypes = pIFamily->GetFamilyTypes();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(familyTypes.size() >= 1, L"族中至少需要一个FamilyType",L"GDMPLab",L"2024-03-30");

    // 退出编辑模式
    {
        OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"退出编辑环境"));

        // 删除当前文档里的轮廓线
        std::vector<IModelLine*> modelLines;
        ProfileUsedModelLineUtils::GetStructureProfileModelLinesInCurrDoc(pDoc, modelLines);
        FOR_EACH(pModelLine, modelLines)
        {
            ElementId modelLineId = pModelLine->GetOwnerElement()->GetElementId();
            bool bOk = pDoc->DeleteElement(modelLineId);
            DBG_WARN_AND_RETURN_FALSE_UNLESS(bOk, L"删除轮廓线失败",L"GDMPLab",L"2024-03-30");
        }

        IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::NewViewCustomizedProfileModeType);
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pEditMode, L"pEditMode为空",L"GDMPLab",L"2024-03-30");

        pEditMode->EndEditing(pDoc);

        ut->Commit();
    }

    UserTransactionGroupUtils::CommitLatestActive(pDoc);
    pUIDoc->UpdateView();

    // 进入创建柱的命令
    ICommandManager* pCommandManager = ICommandManager::Get();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pCommandManager, L"pCommandManager为空",L"GDMPLab",L"2024-03-30");

    CommandParameters cmdParameters;
    cmdParameters[ID_CMD_PARAM_FAMILY_NAME] = familyName;
    cmdParameters[ID_CMD_PARAM_INSTANCE_TYPE] = familyTypes[0]->GetName();
    pCommandManager->SendCommand(ID_CMD_DRAW_STRUCTURE_VERTICAL_COLUMN, cmdParameters);

    return nullptr;
}
